package com.sun.commons.utils;


import com.sun.dto.users.RoleDto;
import com.sun.dto.users.UserDto;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * MP自动填充Handler
 *
 * @Author whsunchunbo@qq.com
 * @CreateTime 2025/9/7 20:27
 */
@Component
@Slf4j
public class JwtTokenUtil {
    public static final String CLAIM_KEY_USERID = "userId";
    public static final String CLAIM_KEY_USERNAME = "username";
    public static final String CLAIM_KEY_CREATED = "created";
    public static final String CLAIM_KEY_ROLES = "roles";
    public static final String CLAIM_KEY_NAME = "name";
    public static final String CLAIM_KEY_TYPE = "type";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 从token中获取用户名
     *
     * @param token
     * @return
     */
    public Long getUserIdFromToken(String token) {
        Long serId;
        try {
            Claims claims = getClaimsFromToken(token);
            serId = Long.valueOf(claims.getSubject().toString());
        } catch (Exception e) {
            serId = null;
        }
        return serId;
    }

    /**
     * 从token中获取用户名
     *
     * @param token
     * @return
     */
    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.get(CLAIM_KEY_USERNAME).toString();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 获取token的claims
     *
     * @param token
     * @return
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {

            claims = Jwts.parser()
                    .verifyWith(getKey())
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (Exception e) {
            log.error("JWT格式验证失败:{}", token);
            claims = null;
        }
        return claims;
    }

    /**
     * 根据claims生成token
     *
     * @param claims
     * @return
     */
    private SecretKey getKey() {
        return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
    }

    private String generateToken(Map<String, Object> claims) {

        return Jwts.builder()
                .signWith(getKey())
                .subject(claims.get(CLAIM_KEY_USERID).toString())
                .claims(claims).expiration(new Date(System.currentTimeMillis() + expiration * 1000))  //
                .compact();

    }

    /**
     * 根据userDetails生成token
     *
     * @param userDetails
     * @return
     */


    public String generateToken(UserDto user) {
        Map<String, Object> claims = new java.util.HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, user.username());
        claims.put(CLAIM_KEY_USERID, user.id());


        claims.put(CLAIM_KEY_NAME, user.name());
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_TYPE, user.type());
        List<String> roles = user.roles().stream().map(RoleDto::code).toList();
        claims.put(CLAIM_KEY_ROLES, roles);
        return generateToken(claims);
    }


    public boolean isTokenExpired(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration().before(new Date());
    }

    public boolean canRefreshToken(String token) {
        return !isTokenExpired(token);
    }

    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

}
